package foo.bar.wiki.web.action.general;

import foo.bar.wiki.web.action.BaseActionBean;
import foo.bar.wiki.plugins.UserRegistrationPlugin;
import foo.bar.wiki.domain.User;
import foo.bar.wiki.services.UserService;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.*;
import com.google.code.kaptcha.Constants;

/**
 * @author tmjee
 * @version $Date$ $Id$
 */
public class SignupActionBean extends BaseActionBean {

    public static final String VIEW = "/general/signup.jsp";

    private UserService userService;

    @ValidateNestedProperties({
        @Validate(field="username", required = true, trim = true, on={"signup"}),
        @Validate(field="password", required = true, trim = true, on={"signup"}),
        @Validate(field="email", required = true, trim = true, on={"signup"})
    })
    private User user;

    @Validate(required=true, trim=true, on={"signup"})
    private String confirmPassword;

    @Validate(required=true, trim=true, on={"signup"})
    private String captcha;


    @DefaultHandler
    public Resolution view() {
        return new ForwardResolution(generateThemePath(VIEW));
    }


    
    public Resolution signup() {
        userService.signup(user, getContext().getMessages());
        return new RedirectResolution(SignupActionBean.class, "view");    
    }
    @ValidationMethod(on={"signup"})
    public void validation_signup(ValidationErrors errors) {
        if (user.getPassword() != null && confirmPassword != null && (!confirmPassword.equals(user.getPassword()))) {
            errors.add("password", new SimpleError("password and confirm password mismatch"));
        }
        if (captcha == null || (!getSessionAttribute(Constants.KAPTCHA_SESSION_KEY).equals(captcha))) {
            errors.add("captcha", new SimpleError("Captcha mismatch"));    
        }
        userService.validateSignup(user, errors, getContext().getMessages());
    }



    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    public String getCaptcha() {
        return captcha;
    }

    public void setCaptcha(String captcha) {
        this.captcha = captcha;
    }
}
